﻿using System;
using System.Data;
using System.Reflection;
using System.Text;
using System.Web.UI.WebControls;
using H2.NET.Common;
using H2.NET.Web.Workflow.Workflow;
using log4net;
using Ultimus.WFServer;
using H2.NET.Business.Core;
using H2.NET.Data.Common;
using System.Web;


namespace H2.NET.Web.Workflow.Workflow
{
    public partial class IncidentManageLog : DwzCode.BasePage
    {
        public string ProcessSelectName = string.Empty;
        public string From;
        public string To;
        public string Status;

        protected void Page_Load(object sender, EventArgs e)
        {
            var action = AksRequest.GetQueryString("action");
            if (action == "ExportExel")
            {
                DataTable dt = PagedQuery();
                CreateExcel(dt, DateTime.Now.ToString("yyyyMMdd") + "报表.xls");
            }
            if (action == "")
            {
                Expression exp = new Expression();
                exp &= t_log_IncidentManage._ID != 0;
                rpt_ManagerLog.DataSource = PagedQuery();
                rpt_ManagerLog.DataBind();

                clsCmm.clsDB.Storage("bpmDB");
                var dtProcesses = clsCmm.clsDB.Query("SELECT DISTINCT PROCESSNAME FROM PROCESSES");
                rptProcesses.DataSource = dtProcesses;
                rptProcesses.DataBind();
            }
        }

        private string getExportWhere() 
        {
            string where = "";



            return where;
        }

        private string getWhere() 
        {
            string where = "";
            string process = AksRequest.GetFormString("processName");
            string status = AksRequest.GetFormString("Status");
            string from = AksRequest.GetFormString("incidentNoFrom");
            string to = AksRequest.GetFormString("incidentNoTo");

            if (!String.IsNullOrEmpty(process))
            {
                ProcessSelectName = process.Trim();
                where += " and Process like '%" + process + "%'";
            }
            if (!String.IsNullOrEmpty(from))
            {
                From = from;
                where += " and Incident >= " + from;
            }

            if (!String.IsNullOrEmpty(to))
            {
                To = to;
                where += " and Incident <=" + to;
            }

            if (!String.IsNullOrEmpty(status))
            {
                Status = status;
                where += " and Status = '" + status + "'";
            }

            return where;
        }

        private DataTable PagedQuery()
        {

            string sql = "select Process as 流程名, Incident as 实例号, Action as 干预事件, Description as 干预描述, Creator as 操作人, CreateOn as 操作时间, (case Status when 1 then '成功' when 0 then '失败' END) as 状态 from t_log_IncidentManage  where 1=1";

            string where = getWhere();

            if (where != "")
            {
                sql += where;
            }

            clsCmm.clsDB.Storage("oleDB");
            TotalItemCount = Convert.ToInt32(clsCmm.clsDB.Query("select count(*) from t_log_IncidentManage where 1=1" + where).Rows[0][0]);
            PageNumber = Convert.ToInt32(Request.Form["pageNum"] ?? "1");

            Pager1.TotalItemCount = TotalItemCount;
            Pager1.PageSize = PageSize;
            Pager1.PageNumber = PageNumber;
            return clsCmm.clsDB.Query(AppendForPaged(sql, PageSize * (PageNumber - 1) + 1, PageSize * PageNumber));

        }

        private string AppendForPaged(string sqlstr, int start, int end)
        {
            var orderby = "操作时间 desc";

            return string.Format(";with temp as(\r\n" +
                "	select row_number() over(order by sub.{3}) as 序号, sub.* from ({0}) sub\r\n)\r\n" +
                "select * from temp where 序号 between {1} and {2}", sqlstr, start, end, orderby);
        }


        public void CreateExcel(DataTable datatable, string fileName)
        {
            HttpResponse resp = Page.Response;
            resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            resp.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
            string colHeaders = "", lsItem = "";

            ////定义表对象与行对象，同时用DataSet对其值进行初始化
            //DataTable dt = ds.Tables[0];
            var myRow = datatable.Select();//可以类似dt.Select("id>10")之形式达到数据筛选目的
            int i;
            var cl = datatable.Columns.Count;

            //取得数据表各列标题，各标题之间以t分割，最后一个列标题后加回车符
            for (i = 0; i < cl; i++)
            {
                if (i == (cl - 1))//最后一列，加n
                {
                    colHeaders += datatable.Columns[i].Caption + "\n";
                }
                else
                {
                    colHeaders += datatable.Columns[i].Caption + "\t";
                }

            }
            resp.Write(colHeaders);
            //向HTTP输出流中写入取得的数据信息

            //逐行处理数据 
            foreach (var row in myRow)
            {
                //当前行数据写入HTTP输出流，并且置空ls_item以便下行数据   
                for (i = 0; i < cl; i++)
                {
                    if (i == (cl - 1))//最后一列，加n
                    {
                        lsItem += row[i] + "\n";
                    }
                    else
                    {
                        lsItem += row[i] + "\t";
                    }

                }
                resp.Write(lsItem);
                lsItem = "";

            }
            resp.End();
        }

    }
}